#define _CRT_SECURE_NO_WARNINGS 1
#include"List.h"

ListNode* BuyListNode(LTDataType x)
{
	ListNode* Newnode = (ListNode*)malloc(sizeof(ListNode));
	Newnode->data = x;
	Newnode->next = NULL;
	Newnode->prev = NULL;

	return Newnode;
}

void ListDestory(ListNode* pHead)
{
	ListNode* cur = pHead->next;
	while (cur!=pHead)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}

	free(pHead);
}

ListNode* ListCreate()
{
	ListNode* head = (ListNode*)malloc(sizeof(ListNode));
	head->next = head;
	head->prev = head;
	return head;
}

void ListPrint(ListNode* pHead)
{
	ListNode* cur = pHead->next;
	while (cur!=pHead)
	{
		printf("%d ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

void ListPushBack(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* tail = pHead->prev;
	ListNode* Newnode = BuyListNode(x);

	tail->next = Newnode;
	Newnode->prev = tail;
	Newnode->next = pHead;
	pHead->prev = Newnode;
}

void ListPushFront(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* frist = pHead->next;
	ListNode* Newnode= BuyListNode(x);

	Newnode->prev = pHead;
	pHead->next = Newnode;
	Newnode->next = frist;
	frist->prev = Newnode;
}

bool Empty(ListNode* pHead)
{
	assert(pHead);
	return pHead->next == NULL;
}

void ListPopBack(ListNode* pHead)
{
	assert(pHead);
	assert(!Empty(pHead));
	ListNode* tail = pHead->prev;
	ListNode* tailprev = tail->prev;

	free(tail);
	tailprev->next = pHead;
	pHead->prev = tailprev;
}

void ListPopFront(ListNode* pHead)
{
	assert(pHead);
	assert(!Empty(pHead));
	ListNode* first = pHead->next;
	ListNode* second = first->next;

	 free(first);
	pHead->next = second;
	second->prev = pHead;
   
}

ListNode* ListFind(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* cur = pHead->next;
	while (cur != pHead)
	{
		if (cur->data = x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* prev = pos->prev;
	ListNode* Newnode = BuyListNode(x);

	prev->next = Newnode;
	Newnode->prev = prev;
	Newnode->next = pos;
	pos->prev = Newnode;
}

void ListErase(ListNode* pos)
{
	assert(pos);
	ListNode* prev = pos->prev;
	ListNode* next = pos->next;

	prev->next = next;
	next->prev = prev;
	free(pos);
}